package Daos;

import Beans.Usuario;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author angel
 */
public class DaoBase {

    static Connection conn;
    static String url = "jdbc:mysql://127.0.0.1/";
    static String base = "pictonary";
    static String user = "server";
    static String pass = "hola123";

    /**
     *
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public boolean conectar(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url + base, user, pass);
            return true;
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        } catch (ClassNotFoundException ex) {
            System.out.println(ex.getMessage());
        } return false;
    }

    /**
     *
     * @throws SQLException
     */
    public void desconectar() throws SQLException{
        conn.close();
    }

    /**
     *
     * @param u
     * @return
     * @throws SQLException
     */
    public int insertar(Usuario u) throws SQLException{
        String sql = "INSERT INTO `Usuarios`(nombre, pass) "
                + "VALUES(?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, u.getNombre());
        ps.setString(2, u.getPass());
        return ps.executeUpdate();

    }

    /**
     *
     * @return
     * @throws SQLException
     */
    public List<Usuario> selectAll() throws SQLException{
        List<Usuario> all = new ArrayList<Usuario>();
        String sql = "SELECT * FROM `Usuarios`";
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while(rs.next()){
            Usuario u = new Usuario();
            u.setIdUsuario(rs.getInt(1));
            u.setNombre(rs.getString(2));
            u.setPass(rs.getString(3));
            u.setIp(rs.getString(4));
            u.setIdPartida(rs.getInt(5));
            u.setScore(rs.getInt(6));
            all.add(u);
        }
        return all;

    }

    /**
     *
     * @param u
     * @return
     * @throws SQLException
     */
    public boolean validar(Usuario u) throws SQLException{
        PreparedStatement ps = conn.prepareStatement("select * from `Usuarios` where nombre=? and pass=?");

        ps.setString(1,u.getNombre());
        ps.setString(2,u.getPass());

        ResultSet rs = ps.executeQuery();

        return rs.next();

    }

    /**
     *
     * @param u
     * @return
     * @throws SQLException
     */
    public int borrar(Usuario u) throws SQLException{

    PreparedStatement ps = conn.prepareStatement
            ("DELETE FROM `Usuarios` WHERE idUsuario = ?");
    ps.setInt(1,u.getIdUsuario());

    return ps.executeUpdate();



    }


}

